package baiqitun.stupro.common.util;

import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;

/**
 *
 * @author kedaji
 */
public class AuthUtil {
    /**
     * 从用户认证信息里获取用户名
     * @param authentication 认证信息
     * @return 用户名
     */
    public static String getUsername(Authentication authentication){
        if (authentication == null){
            throw new InsufficientAuthenticationException("请登录");
        }
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        return userDetails.getUsername();
    }

    public static Collection<? extends GrantedAuthority> getAuthorities(Authentication authentication){
        Object principal = authentication.getPrincipal();
        Collection<? extends GrantedAuthority> authorities = null;
        if (principal instanceof UserDetails){
            UserDetails userDetails = (UserDetails) principal;
            authorities = userDetails.getAuthorities();
        }
        else {
            authorities = authentication.getAuthorities();
        }
        return authorities;
    }
}
